package service

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_check_agent/handler"
)

func PostPortCheckAgent(context *gin.Context) {

	var param handler.CheckDataAgent
	err := context.BindJSON(&param) // 前后端交互参数
	if err != nil {                 // 错误处理
		log.Printf("ERROR: Port check failed, error is %v", err)
		context.JSON(500, gin.H{"err": err})
		return
	}

	portMap := map[string]string{
		"process": "10905",
		"port":    "10914",
		"node":    "10900",
		"sys":     "10916",
	}

	var reOutCome string

	for _, v := range param.IP {

		targetUrl := "http://" + v + ":" + portMap[param.Type] + "/metrics"
		_, err := handler.GetData(targetUrl,param.TimeOut)
		var reOutComeSingle string
		if err != nil {
			reOutComeSingle = v + " " + param.Type + " port check failed"
		} else {
			reOutComeSingle = v + " " + param.Type + " port check pass"
		}
		reOutCome = reOutCome + reOutComeSingle + "\n"
	}

	type jsonData struct {
		Code int
		Data string
	}
	data := jsonData{
		Code: 200,
		Data: reOutCome,
	}
	context.JSON(http.StatusOK, data)

}
